<?php

namespace App\Http\Controllers\Kms\App\Auth;

use App\Http\Validate\Kms\Auth\AuthValidate;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Laravel\Passport\ClientRepository;
use Laravel\Passport\Exceptions\OAuthServerException;
use Laravel\Passport\Http\Controllers\AuthorizationController;
use Laravel\Passport\TokenRepository;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class KmsAuthorizationController extends AuthorizationController
{
    /**
     * @param ServerRequestInterface $psrRequest
     * @param Request $request
     * @param ClientRepository $clients
     * @param TokenRepository $tokens
     * @return Response
     * @throws ValidationException
     * @throws OAuthServerException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function authorize(
        ServerRequestInterface $psrRequest,
        Request $request,
        ClientRepository $clients,
        TokenRepository $tokens
    ): Response {
        $params     = (array)AuthValidate::authorizeValidate($psrRequest->getQueryParams());
        $psrRequest = $psrRequest->withQueryParams(array_merge(
            $params,
            [
                "response_type" => "code",
                "scope"         => "",
                "state"         => Str::random(40)
            ]
        ));

        $authRequest = $this->withErrorHandling(function () use ($psrRequest) {
            return $this->server->validateAuthorizationRequest($psrRequest);
        });

        return $this->approveRequest($authRequest, $request->user());
    }


    /**
     * Convert a PSR7 response to a Illuminate Response.
     *
     * @param ResponseInterface $psrResponse
     * @return Response
     * @throws BindingResolutionException
     */
    public function convertResponse($psrResponse): Response
    {
        parse_str(explode("?", $psrResponse->getHeader("Location")[0])[1], $responseData);
        return response()->make(
            ['code' => 200, 'msg' => '', 'data' => $responseData ?: null],
            200,
            ["Content-Type" => "application/json"]
        );

    }
}
